<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Chat Client</title>
</head>
<body>
<p id="cc">在线人数</p>
<script>
    var socket;
    var num=0;
    window.onload = function () {
        var nick = prompt("输入聊天昵称");
        var input = document.getElementById("input");
        input.focus();

        // 初始化客户端套接字并建立连接
        socket = new WebSocket("ws://gjm.glack.net/ws?name="+nick);

        // 连接建立时触发
        socket.onopen = function (event) {
            console.log("Connection open ...");
            //连接成功时定时发送数据包
            xxx();
        }

        // 接收到服务端消息推送时执行
        socket.onmessage = function (event) {
            var msg = event.data;
            var data=JSON.parse(msg);
            var cc = document.getElementById("cc");
            cc.innerHTML=data.summsg;
            if(data.mymsg!=''){
                var node = document.createTextNode('我的信息：'+data.mymsg);
                var div = document.createElement("div");
                div.appendChild(node);
                document.body.insertBefore(div, input);
                input.scrollIntoView();
            }
            if (data.xtmsg!=''){
                var node = document.createTextNode('系统消息:'+data.xtmsg);
                var div = document.createElement("div");
                div.appendChild(node);
                document.body.insertBefore(div, input);
                input.scrollIntoView();
            }
            if (data.notmemsg!=''){
                var node = document.createTextNode('他人消息:'+data.notmemsg);
                var div = document.createElement("div");
                div.appendChild(node);
                document.body.insertBefore(div, input);
                input.scrollIntoView();
            }
        };

        // 连接关闭时触发
        socket.onclose = function (event) {
            console.log("Connection closed ...");
        }

        input.onchange = function () {
            var msg = nick + ": " + input.value;
            // 将输入框变更信息通过 send 方法发送到服务器
            socket.send(msg);
            input.value = "";
        };

    }
    //定时发送数据包防止死去
    function xxx() {
        socket.send('');
        setTimeout(function () {
            console.log('redismess'+num);
            xxx();
        },10000)
    }
    //关闭页面是断开连接
    window.onunload(function () {
        socket.close();
    });
</script>
<input id="input" style="width: 100%;">
</body>
</html>